package com.ht.medicaltreatment.activity

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.BusTag
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.CaiYangAdapter
import com.ht.medicaltreatment.bean.TransportRfidSampleBox
import com.ht.medicaltreatment.utils.EventBusUtils
import com.ht.medicaltreatment.utils.NFCUtils
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.utils.Subscribe
import com.ht.medicaltreatment.utils.ThreadMode
import com.ht.medicaltreatment.utils.UIDUitls
import com.ht.medicaltreatment.view.CaiYangDialog
import com.ht.medicaltreatment.view.ChooseZhuanRuDialog
import com.ht.medicaltreatment.view.ProjectDialog
import com.ht.medicaltreatment.viewmodel.OrderDetailViewModel
import com.xgst.lib.utils.TimeUtils
import com.xgst.lib.utils.showToast
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_caiyang_layout.btnSave
import kotlinx.android.synthetic.main.activity_caiyang_layout.imgNFC
import kotlinx.android.synthetic.main.activity_caiyang_layout.imgYB
import kotlinx.android.synthetic.main.activity_caiyang_layout.includeScan
import kotlinx.android.synthetic.main.activity_caiyang_layout.includeSuccess
import kotlinx.android.synthetic.main.activity_caiyang_layout.recyclerView
import kotlinx.android.synthetic.main.activity_caiyang_layout.tabLine1
import kotlinx.android.synthetic.main.activity_caiyang_layout.tabLine2
import kotlinx.android.synthetic.main.activity_caiyang_layout.tabLine3
import kotlinx.android.synthetic.main.activity_caiyang_layout.tabLine4
import kotlinx.android.synthetic.main.activity_caiyang_layout.tabLine5
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvOrderCode
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvOrderName
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvRemark
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvTab1
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvTab2
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvTab3
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvTab4
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvTab5
import kotlinx.android.synthetic.main.activity_caiyang_layout.tvTips
import kotlinx.android.synthetic.main.include_scan_layout.btnBack
import kotlinx.android.synthetic.main.include_scan_success.tvScanSuccessUIDName
import kotlinx.android.synthetic.main.include_title_layout.imgBack

/*
1、点击样本盒 弹出选择位置框  选择好位置后回显
2、选择位置后，还可以再次选择，但是存入冰箱后，就不能再选择了
3、全部盘点完成，并且都选择位置了，才能点击存入
4、样本盘点模块  - 已经盘点的样本盒不能再次盘点
5、选择位置后，
 */
class CaiYangBaoActivity : BaseActivity(), View.OnClickListener, OnItemClickListener {
    private var list: MutableList<TransportRfidSampleBox> = mutableListOf()

    //private val model by viewModels<InViewModel>()
    private val model by viewModels<OrderDetailViewModel>()
    private lateinit var adapter: CaiYangAdapter
    private var currentPosition = 0
    private var isLabel = true
    private var isOpen = false
    private var id = -1
    private var transportOrderId = -1
    private var scanItemPositon = -1
    private var isSave = false
    private var isNFC = false
    private var isStartNFC = false

    override fun getLayoutId() = R.layout.activity_caiyang_layout

    override fun isViewStup() = true

    override fun init() {
        setTitle("清点采样包")

        recyclerView.layoutManager = GridLayoutManager(this, 4)
        adapter = CaiYangAdapter()
        recyclerView.adapter = adapter
        id = intent.getIntExtra("id", -1)
        initData()

        initNFC()
        ScanUtils.init()
        initClick()
        adapter.setOnItemClickListener(this)

        EventBusUtils.register(this)
    }

    private fun initNFC() {
        if(Build.MODEL != "V9100"){
            isNFC = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)
            if(isNFC){
                NFCUtils(this)
            }
        }
    }

    private fun initData() {
        showProgress()
        model.orderDetail("$id") {
            dismissProgress()
            transportOrderId = it.transportOrder.id
            tvOrderName.text = it.transportOrder.orderName
            tvOrderCode.text = it.transportOrder.orderNumber
            tvRemark.text = it.transportOrder.remarks
            list = it.transportRfidSampleBoxList
            isSave = it.transportOrder.status == 3
            adapter.setNewInstance(list)
        }
    }


    private fun initClick() {
        tvTab1.setOnClickListener(this)
        tvTab2.setOnClickListener(this)
        tvTab3.setOnClickListener(this)
        tvTab4.setOnClickListener(this)
        tvTab5.setOnClickListener(this)
        imgYB.setOnClickListener(this)
        imgNFC.setOnClickListener(this)
        btnBack.setOnClickListener(this)
        btnSave.setOnClickListener(this)
        imgBack.setOnClickListener(this)
    }

    @Subscribe(ThreadMode.MAIN)
    fun onBus(event:String){
        if(event == BusTag.IN){
            adapter.data.get(scanItemPositon).transportStatus = 1
            adapter.notifyItemChanged(scanItemPositon)
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            //放撕标签
            tvTab1 -> {
                isLabel = true
                tvTab1.setTextColor(getColor(R.color.blue))
                tvTab1.textSize = 18f
                tvTab2.textSize = 15f
                tvTab2.setTextColor(getColor(R.color.color99))

                tabLine1.visibility = View.VISIBLE
                tabLine2.visibility = View.GONE

                imgNFC.visibility = View.GONE
                imgYB.visibility = View.VISIBLE

                tvTips.text = "请使用手机NFC/PDA识别防伪标签"
            }
            //样本
            tvTab2 -> {
                isLabel = false
                tvTab2.setTextColor(getColor(R.color.blue))
                tvTab2.textSize = 18f
                tvTab1.textSize = 15f
                tvTab1.setTextColor(getColor(R.color.color99))

                tabLine2.visibility = View.VISIBLE
                tabLine1.visibility = View.GONE

                imgNFC.visibility = View.VISIBLE
                imgYB.visibility = View.INVISIBLE
                tvTips.text = "请使用手机NFC/PDA识别样本标签盒"
            }
            //全部
            tvTab3 -> {
                currentPosition = 0
                tvTab3.setTextColor(getColor(R.color.blue))
                tvTab3.textSize = 18f
                tabLine3.visibility = View.VISIBLE

                tvTab4.textSize = 15f
                tvTab4.setTextColor(getColor(R.color.color99))
                tabLine4.visibility = View.GONE

                tvTab5.textSize = 15f
                tvTab5.setTextColor(getColor(R.color.color99))
                tabLine5.visibility = View.GONE
                adapter.setNewInstance(list)
            }
            //已盘点
            tvTab4 -> {
                currentPosition = 1
                tvTab4.setTextColor(getColor(R.color.blue))
                tvTab4.textSize = 18f
                tabLine4.visibility = View.VISIBLE

                tvTab3.textSize = 15f
                tvTab3.setTextColor(getColor(R.color.color99))
                tabLine3.visibility = View.GONE

                tvTab5.textSize = 15f
                tvTab5.setTextColor(getColor(R.color.color99))
                tabLine5.visibility = View.GONE
                val overList = list.filter { it.transportStatus != 0 }
                adapter.setNewInstance(overList.toMutableList())
            }
            //未盘点
            tvTab5 -> {
                currentPosition = 2
                tvTab5.setTextColor(getColor(R.color.blue))
                tvTab5.textSize = 18f
                tabLine5.visibility = View.VISIBLE

                tvTab4.textSize = 15f
                tvTab4.setTextColor(getColor(R.color.color99))
                tabLine4.visibility = View.GONE

                tvTab3.textSize = 15f
                tvTab3.setTextColor(getColor(R.color.color99))
                tabLine3.visibility = View.GONE
                val noList = list.filter { it.transportStatus == 0 }
                adapter.setNewInstance(noList.toMutableList())
            }

            imgYB -> {
                if (includeScan.isVisible) {
                    return
                }
                includeScan.visibility = View.VISIBLE
                startCheck()
            }

            imgNFC -> {
                if (includeScan.isVisible) {
                    return
                }
                includeScan.visibility = View.VISIBLE
                isStartNFC = true
                //startCheck()
            }

            btnBack -> {
                includeScan.visibility = View.GONE
                SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                ScanUtils.close()
                disposable?.dispose()
                isOpen = false
            }

            //存入
            btnSave -> {
                if(isSave){
                    showToast("已存入冰箱")
                    return
                }
                val item = adapter.data.find { it.position == null }
                if(item != null){
                    showToast("必须全部盘点并选择冰箱后才可以存入")
                    return
                }
                ProjectDialog(this).show({id,name ->
                    showProgress()
                    model.saveIcebox("$transportOrderId","$id",{
                        dismissProgress()
                        isSave = true
                        btnSave.setBackgroundColor(getColor(R.color.color97))
                        btnSave.isEnabled = false

                        showToast("存入成功")
                    },{
                        dismissProgress()
                        showToast(it)
                    })
                })
            }

            imgBack -> finish()
        }
    }

    private var disposable: Disposable? = null
    private fun startCheck() {
        if (isLabel) {
            disposable = TimeUtils.countDownOneTime(1000 * 5, {
                ScanUtils.close()
                //标签损坏Dialog
                CaiYangDialog(this).show({
                    startCheck()
                })
            })
        }
        ScanUtils.open { uid ->
            isOpen = true
            ScanUtils.resetItem(uid)
            list.forEachIndexed { index, bean ->
                if(!isLabel){
                    //盘点样本
                    if(bean.rfidCode == uid && bean.transportStatus == 0){
                        SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                        includeScan.visibility = View.GONE
                        ScanUtils.close()
                        val intent = Intent(this, ScanActivity::class.java)
                        intent.putExtra("uid", list.get(index).rfidCode)
                        //转入:TRANSPORTTO;转出:TRANSPORT
                        intent.putExtra("from", "TRANSPORTTO")
                        intent.putExtra("orderId", transportOrderId)
                        //记录位置，用来回显数据时  局部刷新
                        scanItemPositon = index
                        startActivity(intent)
                    }else{
                        SoundUtils.playSound(SoundUtils.SOUND_ERROR)
                    }
                }else{
                    //防撕标签
                    if(bean.tearCode == uid && bean.transportStatus == 0){
                        SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                        includeScan.visibility = View.GONE

                        ScanUtils.close()
                        disposable?.dispose()
                        includeSuccess.visibility = View.VISIBLE
                        tvScanSuccessUIDName.text = list.get(index).name
                        TimeUtils.countDownOneTime(2000, {
                            includeSuccess.visibility = View.GONE
                        })
                        //盘点样本盒
                        showProgress()
                        model.check("${list.get(index).id}",{
                            dismissProgress()
                            list.get(index).transportStatus = 1
                            setAdapter()
                        },{
                            dismissProgress()
                            showToast(it)
                        })
                    }else{
                        SoundUtils.playSound(SoundUtils.SOUND_ERROR)
                    }
                }
            }
        }
    }

    private fun setAdapter() {
        when (currentPosition) {
            //全部
            0 -> {
                adapter.notifyDataSetChanged()
            }
            //已盘点
            1 -> {
                val overList = list.filter { it.transportStatus != 0 }
                adapter.setNewInstance(overList.toMutableList())
            }
            //未盘点
            2 -> {
                val noList = list.filter { it.transportStatus == 0 }
                adapter.setNewInstance(noList.toMutableList())
            }
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if(!isNFC || !isStartNFC)return
        //当该Activity接收到NFC标签时，运行该方法
        //调用工具方法，读取NFC数据
        var uid: String = NFCUtils.readNFCId(intent)
        LogUtils.i(uid)
        if(uid.length != 8){
            uid = UIDUitls.sort(uid)
        }
        list.forEachIndexed { index, bean ->
            if(!isLabel){
                //盘点样本
                if(bean.rfidCode == uid && bean.transportStatus == 0){
                    SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                    includeScan.visibility = View.GONE
                    ScanUtils.close()
                    val intent = Intent(this, ScanActivity::class.java)
                    intent.putExtra("uid", list.get(index).rfidCode)
                    //转入:TRANSPORTTO;转出:TRANSPORT
                    intent.putExtra("from", "TRANSPORTTO")
                    intent.putExtra("orderId", transportOrderId)
                    //记录位置，用来回显数据时  局部刷新
                    scanItemPositon = index
                    startActivity(intent)
                }else{
                    SoundUtils.playSound(SoundUtils.SOUND_ERROR)
                }
            }else{
                //防撕标签
                if(bean.tearCode == uid && bean.transportStatus == 0){
                    SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                    includeScan.visibility = View.GONE

                    ScanUtils.close()
                    disposable?.dispose()
                    includeSuccess.visibility = View.VISIBLE
                    tvScanSuccessUIDName.text = list.get(index).name
                    TimeUtils.countDownOneTime(2000, {
                        includeSuccess.visibility = View.GONE
                    })
                    //盘点样本盒
                    showProgress()
                    model.check("${list.get(index).id}",{
                        dismissProgress()
                        list.get(index).transportStatus = 1
                        setAdapter()
                    },{
                        dismissProgress()
                        showToast(it)
                    })
                }else{
                    SoundUtils.playSound(SoundUtils.SOUND_ERROR)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBusUtils.unregister(this)
        ScanUtils.close()
        isOpen = false
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if(isSave){
            showToast("已存入，无法再修改位置")
            return
        }
        val item = adapter.getItem(position) as TransportRfidSampleBox
        if(item.transportStatus == 0){
            showToast("还未盘点")
            return
        }
        //选择位置Dialog
        ChooseZhuanRuDialog(this).show {name,id,checked ->
            item.position = name
            adapter.notifyItemChanged(position)
            showProgress()
            if(checked){
                model.saveMultiLocation(id,"$transportOrderId","${item.id}",{
                    dismissProgress()
                },{
                    dismissProgress()
                    showToast(it)
                })
            }else{
                model.saveSingleLocation(id,"${item.id}","${item.name}",{
                    dismissProgress()
                },{
                    dismissProgress()
                    showToast(it)
                })
            }
        }
    }
}
